package com.qmhl.toolposition.activity

import android.app.ProgressDialog
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.widget.Toast
import com.hjq.toast.Toaster
import com.qmhl.toolposition.R
import com.qmhl.toolposition.base.BaseActivity
import com.qmhl.toolposition.databinding.ActivityOneKeyLoginBinding
import com.qmhl.toolposition.utils.PUtils
import com.qmhl.toolposition.utils.PreferenceUtil
import com.qmhl.toolposition.utils.umeng.AuthPageConfig
import com.qmhl.toolposition.utils.umeng.BaseUIConfig
import com.qmhl.toolposition.utils.umeng.Constant
import com.qmhl.toolposition.utils.umeng.ExecutorManager
import com.qmhl.toolposition.utils.umeng.HttpUtil
import com.qmhl.toolposition.utils.umeng.MockRequest.getPhoneNumber
import com.umeng.commonsdk.utils.UMUtils
import com.umeng.umverify.UMResultCode
import com.umeng.umverify.UMVerifyHelper
import com.umeng.umverify.listener.UMTokenResultListener
import com.umeng.umverify.model.UMTokenRet
import org.json.JSONException
import org.json.JSONObject


/**
 * @author: lqhl
 * @createTime: 2023-11-03  16:23
 * @description: 一键登录
 */
class OneKeyLoginActivity : BaseActivity() {


    private var TAG = "OneKeyLoginActivity"

    /**
     * 友盟
     * **/
    private var mTvResult: String? = null
    private var mPhoneNumberAuthHelper: UMVerifyHelper? = null
    private var mProgressDialog: ProgressDialog? = null
    private var mTokenResultListener: UMTokenResultListener? = null
    private var mUIType: Constant.UI_TYPE? = null
    private var mUIConfig: AuthPageConfig? = null


    private lateinit var binding: ActivityOneKeyLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityOneKeyLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }


    override fun initData() {
        super.initData()
        //设置下划线
        binding.tvVerificationCodeLogin.paint.flags = Paint.UNDERLINE_TEXT_FLAG

        binding.tvOneKeyAgreement.text = getClickableSpan()
        binding.tvOneKeyAgreement.movementMethod = LinkMovementMethod.getInstance();

        sdkInit()
        mUIType = Constant.UI_TYPE.CUSTOM_VIEW
        mUIConfig = BaseUIConfig.init(mUIType, this, mPhoneNumberAuthHelper)
        oneKeyLogin()
    }


    /**
     * 进入app就需要登录的场景使用
     */
    private fun oneKeyLogin() {
        mPhoneNumberAuthHelper =
            UMVerifyHelper.getInstance(applicationContext, mTokenResultListener)
        mUIConfig!!.configAuthPage()
        getLoginToken(5000)
    }

    /**
     * 拉起授权页
     *
     * @param timeout 超时时间
     */
    fun getLoginToken(timeout: Int) {
        mPhoneNumberAuthHelper!!.getLoginToken(this, timeout)
        showLoadingDialog("正在唤起授权页")
    }


    fun showLoadingDialog(hint: String?) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog(this)
            mProgressDialog!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
        }
        mProgressDialog!!.setMessage(hint)
        mProgressDialog!!.setCancelable(true)
        mProgressDialog!!.show()
    }


    fun hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog!!.dismiss()
        }
    }

    fun getResultWithToken(token: String?) {
        ExecutorManager.run(Runnable {
            val result: String = getPhoneNumber(token)
            runOnUiThread {
                mTvResult = "登陆成功：$result"
                mPhoneNumberAuthHelper!!.quitLoginPage()
            }
        })
    }


    fun sdkInit() {
        mTokenResultListener = object : UMTokenResultListener {
            override fun onTokenSuccess(s: String) {
                hideLoadingDialog()
                var tokenRet: UMTokenRet? = null
                try {
                    tokenRet = UMTokenRet.fromJson(s)
                    if (UMResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                        Log.i("TAG", "唤起授权页成功：$s")
                    }
                    if (UMResultCode.CODE_GET_TOKEN_SUCCESS == tokenRet.code) {
                        Log.i("TAG", "获取token成功：$s")
                        getResultWithToken(tokenRet.token)
                        mUIConfig!!.release()
                        //登录质量分
                        val token = tokenRet.token
                        Thread {
                            val jo = JSONObject()
                            try {
                                jo.putOpt("token", token)
                                jo.putOpt("appkey", UMUtils.getAppkey(this@OneKeyLoginActivity))
                                jo.putOpt(
                                    "verifyId",
                                    mPhoneNumberAuthHelper!!.getVerifyId(this@OneKeyLoginActivity)
                                )
                                val message: String =
                                    HttpUtil.postRequest(
                                        "https://ai.login.umeng.com/api/demo/info",
                                        jo
                                    )
                                Log.d("jessie", "获取登录质量分$message")
                            } catch (e: JSONException) {
                            }
                        }.start()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                Log.e(TAG, "获取token失败：$s")
                hideLoadingDialog()
                var tokenRet: UMTokenRet? = null
                mPhoneNumberAuthHelper!!.quitLoginPage()
                try {
                    tokenRet = UMTokenRet.fromJson(s)
                    if (UMResultCode.CODE_ERROR_USER_CANCEL == tokenRet!!.getCode()) {
                        //模拟的是必须登录 否则直接退出app的场景
                        finish()
                    } else {
                        val pIntent =
                            Intent(this@OneKeyLoginActivity, VerifiCodeLoginActivity::class.java)
                        startActivityForResult(pIntent, 1002)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                mUIConfig!!.release()
            }
        }
        mPhoneNumberAuthHelper = UMVerifyHelper.getInstance(this, mTokenResultListener)
    }


    private fun startAgreementActivity(title: String, url: String) {
        val intent = Intent(OneKeyLoginActivity@ this, AgreementActivity::class.java)
        intent.putExtra("title", title)
        intent.putExtra("url", url)
        startActivity(intent)
    }


    private fun getClickableSpan(): SpannableString? {
        val spannableString =
            SpannableString("请阅读《用户协议》 《隐私协议》以及《会员协议》并授权使用本机号码登录，同意后请在左边勾选")
        val clickableSpan1: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startAgreementActivity(
                    PUtils.Config.userAgreement_title,
                    PUtils.Config.userAgreement_assert
                )
            }

            //重写该方法去掉下划线
            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = false
            }
        }
        val clickableSpan2: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startAgreementActivity(
                    PUtils.Config.privacyAgreement_title,
                    PUtils.Config.privacyAgreement_assert
                )
            }

            //重写该方法去掉下划线
            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = false
            }
        }
        val clickableSpan3: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startAgreementActivity(
                    PUtils.Config.payAgreement_title,
                    PUtils.Config.payAgreement_assert
                )
            }

            //重写该方法去掉下划线
            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = false
            }
        }
        //设置文字的点击事件
        spannableString.setSpan(clickableSpan1, 3, 9, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(clickableSpan2, 10, 16, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(clickableSpan3, 18, 24, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        //设置文字的前景色
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.agreementText)),
            3,
            9,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.agreementText)),
            10,
            16,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.agreementText)),
            18,
            24,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        return spannableString
    }


    override fun initListener() {
        super.initListener()
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.btnOneKeyLogin.setOnClickListener {
            val isChecked = binding.cbAgreement.isChecked
            if (!isChecked) {
                Toaster.showShort(PUtils.Toast.SEE_AGREEMENT_AND_LOGIN)
            }

        }

        binding.tvVerificationCodeLogin.setOnClickListener {

            startActivity(Intent(this, VerifiCodeLoginActivity::class.java))

        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1002) {
            if (resultCode == 1) {
                mTvResult = "登陆成功：" + data!!.getStringExtra("result")
            } else {
                //模拟的是必须登录 否则直接退出app的场景
                finish()

            }


        }
    }

    override fun onResume() {
        super.onResume()
        mUIConfig!!.onResume()
    }

}